package com.mcmaster.android.data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class TourDatabase {
	// Members
	private static int file_id_;
	private static Context context_;
	private final static String DBFILE = "tourdb.txt";
	// Loads Tour data from text file
	public static void init(Context ctx, int resourceID) {
		file_id_ = resourceID;
		context_ = ctx;
		
		try {
		    File root = Environment.getExternalStorageDirectory();
		    File gpxfile = new File(root, DBFILE);
		    if (!gpxfile.exists()) {
		    	FileWriter writer = new FileWriter(gpxfile, true);

			    writer.append("");
			    writer.flush();
			    writer.close();
		    }
		    
		} catch (IOException e) {
		    Log.e("HEHIEHI", "Could not write file " + e.getMessage());
		}
	}
	
	public static void addTour(Tour tour) {
        try { // catches IOException below
        	List<String> tour_buildings = tour.dumpCodes();
        	File root = Environment.getExternalStorageDirectory();
		    File gpxfile = new File(root, DBFILE);
	    	FileWriter writer = new FileWriter(gpxfile, true);
	    	BufferedWriter writerb = new BufferedWriter(writer);

		    writerb.write("name:" + tour.name + "\r\n"); // Only way I could find to do newline
		    writerb.write("description:" + tour.getDescription() + "\r\n");
		    for (int i=0; i<tour_buildings.size(); ++i) {
		    	writerb.write("qr:" + tour.get(i) + "\r\n" );
		    	writerb.newLine();
		        
			}
		    writerb.write("end" + "\r\n");
		    writerb.flush();
		    writerb.close();
		} 
        catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	public static List<String> getTourNames() throws FileNotFoundException {
		List<String> names_ = new ArrayList<String>();
		
		File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ DBFILE);
		FileInputStream fIn = new FileInputStream(f);//context_.openFileInput(f);
		InputStreamReader read_in = new InputStreamReader(fIn);
		
		Scanner scanner 	= new Scanner(read_in);
		String temp;
		
		try {
			while (scanner.hasNextLine()) {
				Scanner line = new Scanner(scanner.nextLine());
				
				line.useDelimiter(":");
				if (line.hasNext()) {
					temp = line.next(); 
					line.findInLine(":(\\s)");
					if (temp.equals("name")) {
						//Log.i("HI", temp);
						
						names_.add(line.next());
					}
				}
			}
		}
		finally {
			scanner.close();
		}
		return names_;
	}
	// Returns the Tour that corresponds to QR code, if no hit, returns null
	public static Tour getTourFromName(String n) throws FileNotFoundException {

		File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ DBFILE);
		FileInputStream fIn = new FileInputStream(f);//context_.openFileInput(f);
		InputStreamReader read_in = new InputStreamReader(fIn);
		
		Scanner scanner 	= new Scanner(read_in);
		String name		 	= "";
		String descrip		= "";
		List<String> qr 	= new ArrayList<String>();
		boolean found_name	= false;
		String temp;
		
		try {
			while (scanner.hasNextLine()) {
				Scanner line = new Scanner(scanner.nextLine());
				
				line.useDelimiter(":");
				if (line.hasNext()) {
					temp = line.next(); 
					line.findInLine(":(\\s)");
					if (temp.startsWith("#")) {
						line.nextLine();
					}
					else if (temp.equals("name")) {
						name = line.next();
						
						if (name.equals(n)) { found_name = true;Log.e("MESS", "found"); } 
					}
					
					if (!found_name) { continue; }
					
					if (temp.equals("qr")) {
						qr.add(line.next());	
					}
					else if (temp.equals("description")) {
						descrip = line.next();
					}
					else if (temp.equals("end")){
//						for (int i=0; i<qr.size(); ++i) {
//							Log.i("DEBUG_INFO", qr.get(i)); 
//						}
						return new Tour(name, descrip, qr);
					}
				}
			}
		}
		finally {
			scanner.close();
		}
		return null;
	}

	
	
}